package com.taplinker.client.crm.adapter;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.taplinker.client.AppConfigContext;
import com.taplinker.client.AppConfigFactory;
import com.taplinker.client.R;
import com.taplinker.client.core.ImageManager;
import com.taplinker.client.core.RecordingManager;
import com.taplinker.client.im.activity.PictureDetailActivity;
import com.taplinker.client.im.domain.EnumMessageType;
import com.taplinker.client.im.protocol.TapLinkerConversation;
import com.taplinker.client.im.rpc.DownloadCommand;
import com.taplinker.client.im.util.SmileyParser;
import com.taplinker.core.rpc.http.client.cache.CacheKey;
import com.taplinker.core.rpc.http.client.cache.HttpCacheDAO;
import com.taplinker.core.rpc.http.client.cache.HttpCacheItem;
import com.taplinker.core.services.DSManager;
import com.taplinker.core.util.ImageUtil;
import com.taplinker.core.util.LogUtil;
import com.taplinker.core.util.TimeUtil;
import com.taplinker.dto.web.MessageListResponse.MessageRes;

public class ChatHistoryListAdapter extends BaseAdapter {
	private Context context;
	private SmileyParser parser;
	private static final int TYP_LEFG = 0;
	private static final int TYP_RIGHT= 1;
	public List<MessageRes> dataList = null;
	private TapLinkerConversation conversation;
	
	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public ChatHistoryListAdapter() {
		super();
	}

	public ChatHistoryListAdapter(Context context,List<MessageRes> data) {
		this.parser = new SmileyParser(context);
		this.context = context;
		dataList = data;

	}

	public int getCount() {
		return dataList.size();
	}

	@Override
	public int getViewTypeCount() {
		return 2;
	}
	
	@Override
	public int getItemViewType(int position) {
		if(((MessageRes)getItem(position)).hasSendVistor())
			return 0;
		else
			return 1;
	}

	public long getItemId(int position) {
		return position;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		final MessageRes currentMsg = dataList.get(position);
		if(null == currentMsg) {
			return null;
		}
		int type = getItemViewType(position);
		ConversationBaseItem holder;
		if(convertView == null){
			holder = new ConversationBaseItem();
			switch(type){
			case TYP_LEFG:
				convertView = LayoutInflater.from(context).inflate(R.layout.chat_list_left_item_history, null);
				holder.name = (TextView) convertView.findViewById(R.id.name_text_tv);
				holder.head = (ImageView) convertView.findViewById(R.id.head_icon_iv);
//				leftItem.status = (ImageView) convertView.findViewById(R.id.receiver_status_iv);
				holder.content = (TextView) convertView.findViewById(R.id.content_text_tv);
				holder.time = (TextView) convertView.findViewById(R.id.time_text_tv);
				holder.img = (ImageView)convertView.findViewById(R.id.content_img_tv);
				holder.soundTime = (TextView)convertView.findViewById(R.id.content_sound_tv);
				break;
			case TYP_RIGHT:
				convertView = LayoutInflater.from(context).inflate(R.layout.chat_list_right_item_history, null);
				holder.name = (TextView) convertView.findViewById(R.id.name_text_tv);
				holder.head = (ImageView) convertView.findViewById(R.id.head_icon_iv);
				holder.state = (TextView) convertView.findViewById(R.id.sender_state_tv);
				holder.content = (TextView) convertView.findViewById(R.id.content_text_tv);
				holder.time = (TextView) convertView.findViewById(R.id.time_text_tv);
				holder.img = (ImageView)convertView.findViewById(R.id.content_img_tv);
				holder.soundTime = (TextView)convertView.findViewById(R.id.content_sound_tv);
				break;
			}
			convertView.setTag(holder);
		}else{
			holder = (ConversationBaseItem) convertView.getTag();
		}
		switch(type){
		case TYP_LEFG:
			resetName(holder.name, true, currentMsg);
			resetHead(holder.head, true, currentMsg);
			resetMsgTime(holder.time, currentMsg);
			holder.content.setVisibility(View.GONE);
			holder.soundTime.setVisibility(View.GONE);
			holder.img.setVisibility(View.GONE);
			if(currentMsg.getType().equalsIgnoreCase(EnumMessageType.IMAGE.getType())) {
				holder.img.setVisibility(View.VISIBLE);
				resetMsgImg(holder.img, currentMsg);
			} else if(currentMsg.getType().equalsIgnoreCase(EnumMessageType.AUDIO.getType())) {
				holder.soundTime.setVisibility(View.VISIBLE);
				resetMsgSound(holder.soundTime, currentMsg);
			} else if(currentMsg.getType().equalsIgnoreCase(EnumMessageType.TEXT.getType())) {
				holder.content.setVisibility(View.VISIBLE);
				resetMsgText(holder.content, currentMsg);
			} else {
				return null;
			}
			break;
		case TYP_RIGHT:
			resetName(holder.name, false, currentMsg);
			resetHead(holder.head, false, currentMsg);
			resetMsgTime(holder.time, currentMsg);
			resetMsgState(holder.state, false, currentMsg);
			holder.content.setVisibility(View.GONE);
			holder.soundTime.setVisibility(View.GONE);
			holder.img.setVisibility(View.GONE);
			if(currentMsg.getType().equalsIgnoreCase(EnumMessageType.IMAGE.getType())) {
				holder.img.setVisibility(View.VISIBLE);
				resetMsgImg(holder.img, currentMsg);
			} else if(currentMsg.getType().equalsIgnoreCase(EnumMessageType.AUDIO.getType())) {
				holder.soundTime.setVisibility(View.VISIBLE);
				resetMsgSound(holder.soundTime, currentMsg);
			} else if(currentMsg.getType().equalsIgnoreCase(EnumMessageType.TEXT.getType())) {
				holder.content.setVisibility(View.VISIBLE);
				resetMsgText(holder.content, currentMsg);
			} else {
				return null;
			}
			break;
		}
		((ObjectBind)convertView.getTag()).setMessage(currentMsg);
		convertView.setBackgroundDrawable(null);
		return convertView;
	}
	
	interface ObjectBind{
		MessageRes getMessage();
		void setMessage(MessageRes message);
		TextView getStateView();
	}
	
	class ConversationBaseItem implements ObjectBind {
		TextView name;		// 用户名
		ImageView head;		// 头像
		ImageView status;	// 客服状态
		TextView state;		// 读取状态
		TextView time;		// 时间
		TextView content;	// 内容
		ImageView img;		// 图片
		TextView soundTime;	// 语音时长
		ProgressBar progressBar;	// 下载进度条
		TextView progress;			// 下载进度
		private MessageRes message;
		@Override
		public MessageRes getMessage() {
			return message;
		}
		@Override
		public void setMessage(MessageRes value) {
			message = value;
		}
		
		@Override
		public TextView getStateView() {
			return state;
		}
	}

	/**
	 * 姓名
	 * @param nameTv
	 * @param isLeftSide
	 * @param msg
	 */
	private void resetName(final TextView nameTv, final Boolean isLeftSide, final MessageRes msg) {
		String user_name;
		if (isLeftSide) {
			user_name = "客户";
		} else {
			user_name = msg.getSendUser();
		}
		nameTv.setText(user_name);
		
	}
	
	/**
	 * 头像
	 * @param headIv
	 * @param isLeftSide
	 * @param msg
	 */
	private void resetHead(final ImageView headIv, final Boolean isLeftSide, final MessageRes msg) {
		if (!isLeftSide) {
			String headIcon = AppConfigFactory.getInstance().getUserInfo().getUserIcon();
			if (headIcon != null && headIcon.trim().length() > 0) {
				String headUrl = AppConfigContext.WEB_DISK_ROOT + headIcon;
				ImageManager.getInstance().loadImage(headUrl, headIv, 45, 45,null);
			}
		}
	}
	
	/**
	 * 消息内容
	 * @param textTv
	 * @param msg
	 */
	private void resetMsgText(final TextView textTv, final MessageRes msg){
		textTv.setText(parser.replace(msg.getContent().toString()));
	}
	
	/**
	 * 语音
	 * @param soundTimeTv
	 * @param msg
	 */
	private void resetMsgSound(final TextView soundTimeTv, final MessageRes msg) {
		String path = getAccessUrl(msg);
		new DownloadCommand(path, new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				final String recPath = (String) msg.obj;
				File file = new File(recPath);
				final int mTime = MediaPlayer.create(context, Uri.fromFile(file)).getDuration();
				int seconds = (int)(mTime/1000);
				soundTimeTv.setText(seconds + "\"");
				// 更改录音气泡长度
				soundTimeTv.setWidth(ImageUtil.dip2px(context, 80) + 2 * seconds);
				
				soundTimeTv.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						RecordingManager.getInstance().playRec(recPath, mTime, null);
					}
				});
				return false;
			}
		}).execute();
	}

	/**
	 * 获取图片路径
	 * @param msg
	 * @return
	 */
	private String getAccessUrl(final MessageRes msg) {
		String url = "";
		if (msg.getContent()!=null && msg.getContent().trim().length()>0 ) {
			url = AppConfigContext.WEB_DISK_ROOT + msg.getContent();
		}
		return url;
	}
	
	/**
	 * 图片
	 * @param imageIv
	 * @param msg
	 */
	private void resetMsgImg(final ImageView imageIv, final MessageRes msg) {
		int maxWidth = DSManager.getDeviceService().getScreenWidth() - 40;
		final String path = getAccessUrl(msg);
		ImageManager.getInstance().loadImage(path, imageIv, maxWidth, maxWidth, new ImageManager.LocalCallBack() {
			
			@Override
			public void callBack(final Object obj) {
				imageIv.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						String url = path;
						try {
							if(url.contains("http://")) {
			    				LogUtil.d("http", "get from remote");
			    				HttpCacheItem item;
									item = HttpCacheDAO.getInstance().getFileIndexItem(CacheKey.getCacheKey(new URL(url).getPath()));
			        			if(item != null&&!item.isTemp())
			        				url = item.getPath();
			        			else
			        				return;
			    			}
						} catch (MalformedURLException e) {
							e.printStackTrace();
						}
//						Intent intent = new Intent(Intent.ACTION_VIEW);  
//						intent.addCategory(Intent.CATEGORY_DEFAULT);
//						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						
//						Uri uri = Uri.parse("file://"+ url);
//						intent.setDataAndType(uri, "image/*");
//						context.startActivity(intent);
						
						Intent intent = new Intent(context, PictureDetailActivity.class);
						intent.putExtra("FilePath", url);
						context.startActivity(intent);
						
					}
				});
			}

			@Override
			public void updateProgres(long planSize, long curSize) {
				
			}

			@Override
			public void no() {
				
			}
		});
			
	}
	
	/**
	 * 消息状态
	 * @param stateTv
	 * @param isLeftSide
	 * @param msg
	 */
	private void resetMsgState(final TextView stateTv, final Boolean isLeftSide, final MessageRes msg) {
		if(!isLeftSide) {
			stateTv.setText("");
			stateTv.setTextColor(0xff4dae4b);
			stateTv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.message_state_bg));
			if (Boolean.parseBoolean(msg.getRead())){
				//stateTv.setText("已读");
				stateTv.setBackgroundResource(R.drawable.input_read);
			}else{
			//	stateTv.setText("未读");
				stateTv.setBackgroundResource(R.drawable.input_round);
			}
		}
	}

	/**
	 * 消息时间
	 * @param timeTv
	 * @param msg
	 */
	private void resetMsgTime(final TextView timeTv, final MessageRes msg) {
		if(!TextUtils.isEmpty(msg.getSendTime())) {
			timeTv.setText(TimeUtil.timeFormat(msg.getSendTime()));
		}
	}
	
	@Override
	public Object getItem(int position) {
		return dataList.get(position);
	}
	
}